#include "Q7_5.h"

bool (*sortMode)(float, float);

_Student::_Student(int id, char *name, float score)
{
	_Student::id = id;
	_Student::name = name;
	_Student::score = score;
	_Student::next = NULL;
}

void _Student::Show()
{
	printf("ID: %d\n", _Student::id);
	printf("Name: %s\n", _Student::name);
	printf("Score: %f\n\n", _Student::score);
}

bool Asc(float a, float b)
{
	return a > b;
}

bool Des(float a, float b)
{
	return a < b;
}

void Swap(Student *a, Student *b)
{
	int id = a->id;
	char *name = a->name;
	float score = a->score;

	a->id = b->id;
	a->name = b->name;
	a->score = b->score;

	b->id = id;
	b->name = name;
	b->score = score;
}

bool Isvalid(Student *head, Student *child)
{
	if(child->score < 0 || child->score > 10)
		return false;

	Student *root;
	root = head;
	while(root->next != NULL)
	{
		if(root->id == child->id)
		{
			return false;
		}
		root = root->next;
	};
	return true;
}

void Add(Student *head, Student *child)
{
	Student *root;
	root = head;
	while(root->next != NULL)
	{
		root = root->next;
	};

	if(Isvalid(head, child))
		root->next = child;
}

void Remove(Student *head, int id)
{
	if(head->id == id)
	{
		head = head->next;
		return;
	}
	Student *forward = head;
	Student *back = head;

	while(forward != NULL)
	{
		if(forward->id == id)
		{
			Student *temp = forward;
			forward = forward->next;
			back->next = forward;
			delete temp;
		}
		else if(back->id == forward->id)
		{
			forward = forward->next;
		}
		else
		{
			back = back->next;
			forward = forward->next;
		}
	};
}

void SortStudent(Student *head, bool mode)
{	
	if(mode)
		sortMode = Asc;
	else
		sortMode = Des;

	for(Student *p = head; p != NULL; p = p->next)
		for(Student *q = p; q != NULL; q = q->next)
		{
			if(sortMode(p->score, q->score))
				Swap(p,q);
		}
}

void Show(Student *head)
{
	Student *root;
	root = head;
	while(root != NULL)
	{
		if(root->score < 5)
		{
			Student *temp = root;
			root = root->next;
			Remove(head, temp->id);
		}else
		{
			root->Show();
			root = root->next;
		}
	};
}

void q7_5_run()
{
	printf("Q7_5\n");
	Student *st1 = new Student(1, "A", 9.5);
	Student *st2 = new Student(2, "B", 4);
	Student *st3 = new Student(1, "C", 10);
	Student *st4 = new Student(3, "D", 8);
	Student *st5 = new Student(4, "E", 11);

	Add(st1, st2);
	Add(st1, st3);
	Add(st1, st4);
	Add(st1, st5);

	SortStudent(st1, false);

	Show(st1);
}